using MediatR;
using WMS.Api.Application.Commands;
using WMS.Common;

namespace WMS.Api.Application.CommandHandlers
{
    /// <summary>
    /// 上传产品图片命令处理程序
    /// </summary>
    public class ProductUploadImageCommandHandler : IRequestHandler<ProductUploadImageCommand, ApiResult<string>>
    {
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly ILogger<ProductUploadImageCommandHandler> _logger;

        public ProductUploadImageCommandHandler(IWebHostEnvironment hostEnvironment, ILogger<ProductUploadImageCommandHandler> logger)
        {
            _hostEnvironment = hostEnvironment;
            _logger = logger;
        }

        public async Task<ApiResult<string>> Handle(ProductUploadImageCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<string>("上传产品图片");

            try
            {
                if (request.File == null || request.File.Length == 0)
                {
                    result.code = StatusCodeEnum.ParamError;
                    result.msg = "请选择要上传的图片文件";
                    return result;
                }

                // 检查文件扩展名
                var fileExtension = Path.GetExtension(request.File.FileName).ToLower();
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".webp" };
                
                if (!allowedExtensions.Contains(fileExtension))
                {
                    result.code = StatusCodeEnum.ParamError;
                    result.msg = "只允许上传jpg、jpeg、png、gif、webp格式的图片";
                    return result;
                }

                // 检查文件大小（限制为5MB）
                if (request.File.Length > 5 * 1024 * 1024)
                {
                    result.code = StatusCodeEnum.ParamError;
                    result.msg = "图片大小不能超过5MB";
                    return result;
                }

                // 创建保存路径
                var webRootPath = _hostEnvironment.WebRootPath;
                var picFolderPath = Path.Combine(webRootPath, "Pic");
                
                // 确保目录存在
                if (!Directory.Exists(picFolderPath))
                {
                    Directory.CreateDirectory(picFolderPath);
                }

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid()}{fileExtension}";
                var filePath = Path.Combine(picFolderPath, fileName);

                // 保存文件
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await request.File.CopyToAsync(fileStream, cancellationToken);
                }

                // 返回可访问的URL路径
                var url = $"/Pic/{fileName}";
                result.Success(url);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传产品图片失败");
                result.code = StatusCodeEnum.Fail;
                result.msg = $"上传产品图片失败：{ex.Message}";
            }

            return result;
        }
    }
} 